<script setup>
import {
  dutyGetRotaServe,
  dutyNewTermServe,
  dutyNextWeekServe,
  dutyIntelligentServe,
  dutyPublishServe,
  dutyContinueServe
} from '@/api/duty'
import { transformSchedule, filterNames } from '@/utils/dutyListChange'
import {
  ArrowDown,
  Refresh,
  Setting,
  Edit,
  Timer,
  Grid,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'
import TimeTableDialog from './components/TimeTableDialog.vue'
import TimeSetDialog from './components/TimeSetDialog.vue'
import ArtificialArrangeDialog from './components/ArtificialArrangeDialog.vue'
import TimeShowDrawer from './components/TimeShowDrawer.vue'
import { useFormatStore } from '@/stores'
import { ref } from 'vue'
import { storeToRefs } from 'pinia'

///*获取值班表格式*/
const formatStore = useFormatStore()
const { format, allWeek, columnLabels } = storeToRefs(formatStore)

/*查时长*/
const timeTableRef = ref()
const onShowTime = () => {
  timeTableRef.value.onShowTime()
}

///*突出显示*/
const allName = ref([])
const highlightName = ref('空')

/////*获取值班表*/
const week = ref(1)
const thisWeek = ref(-1)
const showWeek = ref(1)
/* 空状态0在编辑1已发布2结束修改3 */
const showWeekStatus = ref(0)
const lastWeekStatus = ref(-1)
//
const dutyList = ref([])
const getDutyListLoading = ref(false)
const getDutyList = async () => {
  getDutyListLoading.value = true
  dutyList.value = []
  let obj = {}
  if (thisWeek.value !== -1) {
    obj = { week: week.value }
  }
  const res = await dutyGetRotaServe(obj)
  week.value = res.week
  showWeekStatus.value = res.status
  if (thisWeek.value == -1) {
    thisWeek.value = res.week
    lastWeekStatus.value = res.status
  }
  if (showWeek.value !== week.value) showWeek.value = res.week
  dutyList.value = transformSchedule(res.record)
  allName.value = filterNames(dutyList.value)
  artificialFlag.value = false
  ElMessage.success({ message: '获取值班表成功', offset: 70 })
  getDutyListLoading.value = false
}
getDutyList()

//上下
const getUpDown = (num) => {
  week.value = week.value + num
  getDutyList()
}

////*空闲时间表*/////
const timeShowRef = ref()
const onShowSchedule = () => {
  timeShowRef.value.onShowSchedule()
}
/*更多 */
const timeSetRef = ref()
const onCommand = async (command) => {
  if (command === 'newTerm') {
    await ElMessageBox.confirm(
      '确定开启新学期吗？确认后将清空之前的值班相关信息,人员信息将保留。',
      '温馨提醒',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    await dutyNewTermServe()
    week.value = 1
    thisWeek.value = -1
    showWeek.value = 1
    getDutyList()
    ElMessage.success({ message: '已开始新学期', offset: 70 })
  }
  /*时间段设置*/
  if (command === 'setTime') {
    timeSetRef.value.onSetTime()
  }
}

/* 编辑排班表 */
//打开编辑区
const openEditFlag = ref(false)
//开始排班
const startArrange = async () => {
  await ElMessageBox.confirm('确定开始该周排班吗？', '温馨提醒', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
  await dutyNextWeekServe()
  getDutyList()
  ElMessage.success({ message: '点击对应按钮进行值班安排', offset: 70 })
}
//智能排班
const arrangeLoading = ref(false)
const intelligentArrange = async () => {
  await ElMessageBox.confirm('将进行智能排班', '温馨提醒', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
  arrangeLoading.value = true
  await dutyIntelligentServe()
  getDutyList()
  arrangeLoading.value = false
  ElMessage.success({ message: '智能排班完成', offset: 70 })
}
//发布
const publishDuty = async () => {
  await ElMessageBox.confirm('即将发布该值班表，请确认排班情况，发布后仍可修改', '温馨提醒', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
  await dutyPublishServe()
  if (thisWeek.value == 1 || thisWeek.value == showWeek.value - 1) {
    lastWeekStatus.value = 2
    if (thisWeek.value !== 1 || showWeek.value == 2) {
      thisWeek.value = thisWeek.value + 1
      week.value = thisWeek.value
    }
  }
  getDutyList()
  ElMessage.success({ message: '发布成功', offset: 70 })
}
const conLoading = ref(false)
//延续上一周排班
const continueUseDuty = async () => {
  await ElMessageBox.confirm('确定沿用前一周的值班安排吗？', '温馨提醒', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
  conLoading.value = true
  await dutyContinueServe()
  getDutyList()
  conLoading.value = false
  ElMessage.success({ message: '沿用成功', offset: 70 })
}

//  /  /手动排班
const artificialFlag = ref(false)
const artificialRef = ref()
const artificialArrange = async (day, schedule, editNameList) => {
  artificialRef.value.artificialArrange(showWeek.value, day, schedule, editNameList)
}
</script>

<template>
  <div>
    <!-- header -->
    <div style="display: flex; justify-content: space-between; margin-bottom: 10px">
      <div>
        <strong>今日是第{{ thisWeek }}周</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <strong>查看第&nbsp;</strong>
        <el-select v-model="week" placeholder="Select" style="width: 70px">
          <el-option v-for="item in allWeek" :key="item" :label="item" :value="item" />
        </el-select>
        <strong>&nbsp;周</strong>
        &nbsp;
        <el-button type="primary" size="default" @click="getDutyList()"> 查询 </el-button>
        &nbsp;
        <el-button-group>
          <el-button
            type="primary"
            :icon="ArrowLeft"
            :disabled="showWeek <= 1"
            @click="getUpDown(-1)"
          >
            上一周
          </el-button>
          <el-button type="primary" :disabled="showWeek >= 20" @click="getUpDown(1)">
            下一周<el-icon class="el-icon--right">
              <ArrowRight />
            </el-icon>
          </el-button>
        </el-button-group>
        <strong style="margin-left: 25px"> 筛选显示：</strong>
        <el-select v-model="highlightName" placeholder="Select" style="width: 100px">
          <el-option v-for="(item, index) in allName" :key="index" :label="item" :value="item" />
        </el-select>
      </div>
      <div style="margin-right: 30px; display: flex; justify-content: space-between">
        <el-button-group>
          <el-button type="primary" @click="onShowTime" :icon="Timer">值班时长表</el-button>
          <el-button type="primary" @click="onShowSchedule" :icon="Grid">空闲时间表</el-button>
        </el-button-group>
        <el-dropdown style="margin-left: 10px" @command="onCommand">
          <strong class="el-dropdown__box">
            更多
            <el-icon size="20">
              <ArrowDown />
            </el-icon>
          </strong>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="newTerm" :icon="Refresh">开启新学期</el-dropdown-item>
              <el-dropdown-item command="setTime" :icon="Setting">设置时间段</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <!-- 主 -->
    <div>
      <el-table :data="format" style="width: 100%" border v-loading="getDutyListLoading">
        <!-- 表左边 -->
        <el-table-column label="时间" prop="" width="120px" align="center">
          <template #default="{ row }">
            <div>{{ row.index }}</div>
            {{ row.start + '-' }}{{ row.end }}
          </template>
        </el-table-column>
        <!-- 主体 -->
        <el-table-column align="center">
          <template #header>
            <span style="color: #000; font-size: larger">{{ `第${showWeek}周排班表` }}</span>
            <span style="float: right">
              状态:{{
                showWeekStatus == 0
                  ? '未排班'
                  : showWeekStatus == 1
                    ? '排班中'
                    : showWeekStatus == 2
                      ? '已发布'
                      : '已结束'
              }}
            </span>
          </template>
          <el-table-column
            v-for="(day, index) in dutyList"
            :key="index"
            :label="columnLabels[index]"
            align="center"
          >
            <template v-slot="scope">
              <div :class="artificialFlag == true ? 'cellstyle' : ''">
                <el-button
                  v-if="artificialFlag == true"
                  class="edit_bt"
                  type="warning"
                  :icon="Edit"
                  circle
                  plain
                  @click="artificialArrange(index + 1, scope.$index + 1, day[scope.$index + 1])"
                >
                </el-button>
                <span>
                  <span v-for="(n, index) in day[scope.$index + 1]" :key="index">
                    <el-button
                      class="elbname"
                      :style="{
                        color: n == highlightName ? '#409EFF' : '',
                        marginRight: index % 2 == 0 ? '1px' : '',
                        marginTop: index / 2 + 0.1 > 1 ? '1px' : ''
                      }"
                      style="font-size: larger"
                      text
                      bg
                      auto-insert-space
                    >
                      {{ n }}
                    </el-button>
                    <br v-if="index % 2 != 0" />
                  </span>
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部 -->
    <div class="editFooter">
      <!-- 编辑区按钮 -->
      <div class="editFooter-but" v-if="openEditFlag">
        <el-button
          v-if="showWeekStatus != 3"
          size="default"
          @click="
            () => {
              openEditFlag = false
              artificialFlag = false
            }
          "
          circle
          color="#008836"
        >
          <el-icon>
            <ArrowRight />
          </el-icon>
        </el-button>
        <el-button
          color="#008836"
          size="default"
          @click="startArrange"
          v-if="
            (showWeek == thisWeek + 1 &&
              showWeekStatus == 0 &&
              (lastWeekStatus == -1 || lastWeekStatus >= 2)) ||
            (showWeek == 1 && thisWeek == 1 && showWeekStatus == 0)
          "
        >
          开启排班
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="continueUseDuty"
          v-if="showWeek == thisWeek + 1 && showWeekStatus == 1"
          :loading="conLoading"
        >
          沿用上周
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="intelligentArrange"
          v-if="
            (showWeek == thisWeek + 1 && showWeekStatus == 1) ||
            (showWeek == 1 && thisWeek == 1 && showWeekStatus == 1)
          "
          :loading="arrangeLoading"
        >
          智能排班
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="artificialFlag = true"
          v-if="
            ((showWeek == thisWeek + 1 || showWeek == thisWeek) &&
              (showWeekStatus == 1 || showWeekStatus == 2)) ||
            (showWeek == 1 && thisWeek == 1 && showWeekStatus == 1)
          "
        >
          手动排班
        </el-button>
        <el-button
          color="#008836"
          size="default"
          @click="publishDuty"
          v-if="
            (showWeek == thisWeek + 1 && showWeekStatus == 1) ||
            (showWeek == 1 && thisWeek == 1 && showWeekStatus == 1)
          "
        >
          发布
        </el-button>
      </div>
      <!-- 开启按钮 -->
      <el-button
        v-if="showWeekStatus != 3"
        type="primary"
        size="large"
        circle
        style="margin-right: 10px; font-size: large"
        @click="openEditFlag = true"
      >
        <el-icon>
          <Edit />
        </el-icon>
      </el-button>
    </div>
  </div>
  <!-- 弹窗显示值班时长表 -->
  <TimeTableDialog ref="timeTableRef"></TimeTableDialog>
  <!-- 空闲时段 -->
  <TimeShowDrawer ref="timeShowRef"></TimeShowDrawer>
  <!-- 时间设置 -->
  <TimeSetDialog ref="timeSetRef"></TimeSetDialog>
  <!-- 手动排班 -->
  <ArtificialArrangeDialog ref="artificialRef" @getDutyList="getDutyList"></ArtificialArrangeDialog>
</template>

<style lang="scss" scoped>
.elbname {
  width: 65px;
  height: 25px;
}

.el-dropdown__box {
  display: flex;
  align-items: center;
}

.editFooter {
  width: 100%;
  height: 50px;
  background-color: #fff;

  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.cellstyle {
  display: flex;
  align-items: center;
}

.editFooter-but {
  margin-right: 10px;
}
</style>
